import { expressjwt } from 'express-jwt'
import jwt from 'jsonwebtoken'
import { getUserByEmail } from './db/users.js'
import { ApolloServer } from '@apollo/server'
import { expressMiddleware as apolloMiddleware } from '@apollo/server/express4'
import dotenv from 'dotenv'
import cors from 'cors'
import express from 'express'
import { readFile } from 'node:fs/promises'
import { createCompanyLoader } from './db/companies.js'
import { getUser } from './db/users.js'
import { resolvers } from './apis.js'

dotenv.config()

/// scope for auth
console.log(process.env.SECRET)
const secret = Buffer.from(
	process.env.SECRET || 'IelmLv7Qi7dASmaiAGvyMpFAxRZvxq1Lg7ANdbodBeY=',
	'base64')

const authMiddleware = expressjwt({
	algorithms: ['HS256'],
	credentialsRequired: false,
	secret,
})

async function handleLogin(req, res) {
	const { email, password } = req.body
	const user = await getUserByEmail(email)
	if (!user || user.password !== password) {
		res.sendStatus(401)
	} else {
		const claims = { sub: user.id, email: user.email }
		const token = jwt.sign(claims, secret)
		res.json({ token })
	}
}
/// end scope for auth



/// scope for server start
const PORT = process.env.PORT || 9000

const app = express()
// set this to enable :9000/graphql endpoint
app.use(cors(), express.json(), authMiddleware)


app.post('/login', handleLogin)

const graphql_shema_path = process.env.GRAPHQL_FILEPATH || "./schema.graphql"

const typeDefs = await readFile(graphql_shema_path, 'utf8')

async function getContext({ req }) {
	const companyLoader = createCompanyLoader()

	const ctx = { companyLoader }

	if (req.auth) {
		ctx.user = await getUser(req.auth.sub)
	}

	return ctx
}

const apolloServer = new ApolloServer({ typeDefs, resolvers })
await apolloServer.start()

app.use('/graphql', apolloMiddleware(apolloServer, { context: getContext }))

app.listen({ port: PORT }, () => {
	console.log(`Server running port localhost:${PORT}`)
	console.log(`GraphQL endpoint: http://localhost:${PORT}/graphql`)
})
/// end scope for server start
